package com.zxc.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.model.search.pojos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

import static com.heima.common.constants.ArticleConstants.ARTICLE_SYNC_ES_TOPIC;

@Component
@Slf4j
public class SyncArticleListener {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @KafkaListener(topics = ARTICLE_SYNC_ES_TOPIC)
    public void onMessage(String message) {

        log.info("SyncArticleListener->message={}",message);
        IndexRequest indexRequest = new IndexRequest("app_info_article");
        SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);
        indexRequest.id(searchArticleVo.getId().toString());
        indexRequest.source(message, XContentType.JSON);
        try {
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            log.error("sync es error={}",e);
        }
    }
}
